package com.shenganyuan.smac.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.oklib.utils.Logger.Logger;
import com.oklib.utils.view.ToastUtils;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.Config;
import com.shenganyuan.smac.common.beans.LocationInfo;
import com.shenganyuan.smac.common.data.AnyPrefUtil;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.CommonBottomListDialog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author Damon
 */
public class ActMap extends BaseActivity implements LocationSource, AMapLocationListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.floating_action_button)
    FloatingActionButton floatingActionButton;

    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LocationSource.OnLocationChangedListener mListener;
    private AMap aMap;
    private AMapLocation amapLocation;
    private LatLng currentLatLng;//当前位置

    @Override
    public int getLayoutId() {
        return R.layout.act_map;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    @Override
    public void initData() {
        super.initData();
        setTitle("位置信息");
    }

    @OnClick(R.id.floating_action_button)
    public void onViewClicked() {
        pickMaps(currentLatLng);
    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {

        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }


    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                this.amapLocation = amapLocation;
                // 显示系统小蓝点
                mListener.onLocationChanged(amapLocation);
                displayMarkers();

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Logger.e(errText);
            }
        }
    }
    //根据传入的坐标信息获取锚点

    /**
     * 此处显示多个定位点
     */
    private void displayMarkers() {
        double longitude = getIntent().getDoubleExtra("longitude", 0);
        double latitude = getIntent().getDoubleExtra("latitude", 0);
        if (longitude == 0 || latitude == 0) {
            ToastUtils.showToast(this, "传入数据有误，显示当前位置");
            if (amapLocation == null) {
                ToastUtils.showToast(this, "定位失败");
            }
            longitude = this.amapLocation.getLongitude();
            latitude = this.amapLocation.getLatitude();
        }
        currentLatLng = new LatLng(latitude, longitude);
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(currentLatLng);
        aMap.addMarker(markerOption);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, Config.Data.zoom_to));
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            //设置定位监听
            mlocationClient.setLocationListener(this);
            mLocationOption = new AMapLocationClientOption();
            //设置单次定位
            mLocationOption.setOnceLocation(true);
            //关闭缓存机制
            mLocationOption.setLocationCacheEnable(false);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationOption.setNeedAddress(true);
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 选择地图
     */
    private void pickMaps(LatLng latLng) {
        if (latLng == null || latLng.longitude == 0 || latLng.latitude == 0) {
            ToastUtils.showToast(this, "gps数据不合法");
            return;
        }
        ArrayList<String> datas = new ArrayList<>();
        datas.add("高德");
        datas.add("百度");
        CommonBottomListDialog commonBottomListDialog = CommonBottomListDialog.newInstance(datas);
        commonBottomListDialog.setTitle(getString(R.string.tilte_choose_map));
        commonBottomListDialog.setDefaultCheckValue("");
        commonBottomListDialog.addOnSingleCheckListener(new CommonBottomListDialog.OnSingleCheckListener() {
            @Override
            public void onSingleCheck(int position, String value) {
                LocationInfo locationInfo = AnyPrefUtil.getLocationInfo();
                if (locationInfo != null) {
                    DataConverter.pickMap(mContext, new LatLng(Double.valueOf(locationInfo.latitude), Double.valueOf(locationInfo.longitude)), latLng, position);
                }
            }
        });
        commonBottomListDialog.show(getSupportFragmentManager(), "check_map");
    }
}
